package org.eiahe.hr.performance.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.ehe.common.core.constant.RoleKeyConstants;
import org.ehe.common.core.exception.ServiceException;
import org.ehe.common.core.utils.MapstructUtils;
import org.ehe.common.satoken.utils.LoginHelper;
import org.ehe.system.domain.HrEmployee;
import org.ehe.system.service.IHrEmployeeService;
import org.eiahe.hr.performance.domain.PerformanceCycle;
import org.eiahe.hr.performance.domain.PerformanceLevel;
import org.eiahe.hr.performance.domain.PerformanceResult;
import org.eiahe.hr.performance.domain.PerformanceScore;
import org.eiahe.hr.performance.domain.bo.PerformanceResultBo;
import org.eiahe.hr.performance.domain.vo.PerformanceResultVo;
import org.eiahe.hr.filler.EmployeeNameFiller;
import org.eiahe.hr.performance.mapper.PerformanceCycleMapper;
import org.eiahe.hr.performance.mapper.PerformanceLevelMapper;
import org.eiahe.hr.performance.mapper.PerformanceResultMapper;
import org.eiahe.hr.performance.service.IPerformanceResultService;
import org.ehe.common.core.utils.StringUtils;
import org.ehe.common.mybatis.core.page.PageQuery;
import org.ehe.common.mybatis.core.page.TableDataInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

import java.util.*;

/**
 * 绩效结果Service业务层处理
 *
 * @author zhangnn
 */
@RequiredArgsConstructor
@Service
public class PerformanceResultServiceImpl implements IPerformanceResultService {

    private final PerformanceResultMapper baseMapper;
    private final IHrEmployeeService employeeService;
    private final EmployeeNameFiller employeeNameFiller;
    private final PerformanceCycleMapper cycleMapper;
    private final PerformanceLevelMapper levelMapper;

    @Override
    public PerformanceResultVo queryById(Long resultId) {
        PerformanceResultVo performanceResultVo = baseMapper.selectVoById(resultId);
        employeeNameFiller.fillEmployeeName(
                performanceResultVo,
                PerformanceResultVo::getEmployeeNo,
                PerformanceResultVo::setEmployeeName);
        return performanceResultVo;
    }

    /**
     * 根据员工工号和周期ID查询绩效结果
     *
     * @param employeeNo 工号
     * @param cycleId    周期ID
     * @return 绩效结果
     */
    public PerformanceResult queryByEmployeeAndCycle(String employeeNo, Long cycleId) {
        LambdaQueryWrapper<PerformanceResult> lqw = Wrappers.lambdaQuery();
        lqw.eq(PerformanceResult::getEmployeeNo, employeeNo);
        lqw.eq(PerformanceResult::getCycleId, cycleId);
        lqw.eq(PerformanceResult::getDelFlag, "0");
        return baseMapper.selectOne(lqw);
    }

    private LambdaQueryWrapper<PerformanceResult> buildQueryWrapper(PerformanceResultBo result) {
        LambdaQueryWrapper<PerformanceResult> lqw = Wrappers.lambdaQuery();

        if (!(StpUtil.hasRoleOr(RoleKeyConstants.HR_ROLES.toArray(new String[0])))) {
            // 获取当前登录用户名
            HrEmployee hrEmployee = employeeService.queryByUserId(LoginHelper.getUserId());
            if(Objects.nonNull(hrEmployee)){
                // 添加创建者过滤条件
                lqw.like(PerformanceResult::getEmployeeNo, hrEmployee.getEmployeeNo());
            }
        }

        if (StringUtils.isNotBlank(result.getEmployeeName())) {
            List<String> employeeNos = employeeService.queryByEmployeeName(result.getEmployeeName());
            if (CollUtil.isEmpty(employeeNos)) {
                lqw.eq(PerformanceResult::getEmployeeNo, -1);
            } else {
                lqw.in(PerformanceResult::getEmployeeNo, employeeNos);
            }
        }
        lqw.eq(StringUtils.isNotBlank(result.getEmployeeNo()), PerformanceResult::getEmployeeNo,
                result.getEmployeeNo());
        lqw.eq(result.getLevelId() != null, PerformanceResult::getLevelId, result.getLevelId());
        lqw.eq(StringUtils.isNotBlank(result.getStatus()), PerformanceResult::getStatus, result.getStatus());
        return lqw;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TableDataInfo<PerformanceResultVo> queryPageListVo(PerformanceResultBo result, PageQuery pageQuery) {
        LambdaQueryWrapper<PerformanceResult> lqw = buildQueryWrapper(result);
        Page<PerformanceResultVo> page = baseMapper.selectVoPage(pageQuery.build(), lqw);
        // 添加员工姓名
        employeeNameFiller.fillEmployeeNames(page.getRecords(), PerformanceResultVo::getEmployeeNo,
                PerformanceResultVo::setEmployeeName);
        page.getRecords().forEach(p->{
            PerformanceCycle performanceCycle = cycleMapper.selectById(p.getCycleId());
            if(Objects.nonNull(performanceCycle)){
                p.setCycleName(performanceCycle.getCycleName());
            }
            PerformanceLevel level = levelMapper.selectById(p.getLevelId());
            if(Objects.nonNull(level)){
                p.setLevelName(level.getLevelName());
            }
            if(p.getStatus().equals("0")){
                p.setStatusName("待确认");
            } else {
                p.setStatusName("已确认");
            }
        });

        return TableDataInfo.build(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(PerformanceResultBo result) {
        PerformanceResult add = MapstructUtils.convert(result, PerformanceResult.class);
        return baseMapper.insert(add) > 0;
    }

    @Override
    public Boolean updateByBo(PerformanceResultBo result) {
        PerformanceResult update = MapstructUtils.convert(result, PerformanceResult.class);
        return baseMapper.updateById(update) > 0;
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (ids == null || ids.isEmpty()) {
            return false;
        }
        Long count = this.baseMapper.selectCount(
                new LambdaQueryWrapper<PerformanceResult>()
                        .in(PerformanceResult::getCycleId, ids)
                        .eq(PerformanceResult::getDelFlag, "0"));
        if (count > 0) {
            throw new ServiceException("该周期已被使用，无法删除");
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
